package com.newway.aop;

import com.alibaba.fastjson.JSON;
import com.newway.wechat.context.UserInfo;
import com.newway.wechat.context.UserInfoContext;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.Date;

@Aspect
@Component
public class LogRecordAspect {


    @Pointcut("@annotation(log)")
    public void logPointCut(Log log) {
    }

    @AfterReturning(pointcut = "logPointCut(log)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint,Log log, Object jsonResult) {
        saveLog(joinPoint,log,jsonResult,null);
    }

    @AfterThrowing(pointcut = "logPointCut(log)", throwing = "e")
    public void afterException(JoinPoint joinPoint, Log log,Exception e) {
        saveLog(joinPoint,log,null,e);
    }

    private void saveLog(JoinPoint joinPoint, Log log, Object o, Exception e) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        UserInfo userInfo = UserInfoContext.getUserInfo();
        LogRecordEntity logRecord = new LogRecordEntity();
        logRecord.setCreateDate(new Date());
        logRecord.setUserId(userInfo.getId());
        logRecord.setOperateType(log.operateType());
        logRecord.setOperateDesc(log.operateDesc());
        // 设置方法名称
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        logRecord.setMethod(className + "." + methodName + "()");
        logRecord.setRequestUrl(request.getRequestURI());
        String requestParam = "";
        Object[] args = joinPoint.getArgs();
        if(args!=null && args.length>0){
            for(int i=0;i<args.length;i++){
                requestParam = requestParam + JSON.toJSONString(args[i]);
            }
        }
        logRecord.setRequestParam(requestParam);
        logRecord.setResultStatus("0");
        if(e!=null){
            logRecord.setErrorMsg(e.getMessage());
            logRecord.setResultStatus("1");
        }
        System.out.println(logRecord.toString());
    }


}
